﻿using Prism.Commands;
using Prism.Regions;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Model.DbContext.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using Telerik.Windows.Controls;
using Unity;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class ItemListBomViewModel : ListRegionViewModel<ItemList>
    {
        private readonly int templateType = 2;
        private readonly IItemListService _itemListService;
        private readonly ITemplateSettingService _tempServ;
        private readonly IAchievementService _achievementService;
        private GroupMode _groupMode = GroupMode.mode0;
        private DelegateCommand<object> _modelSelectChangedCommand;
        private DelegateCommand<object> _addItemCommand;
        private DelegateCommand<object> _exportFileCommand;

        private ComboBoxItemModel<Report> _templateSelectObj = null;
        private ObservableCollection<ComboBoxItemModel<Report>> _templateList = null;


        public ItemListBomViewModel(
            IItemListService itemListService, IAchievementService achievementService,ITemplateSettingService tempServ,
            IRegionManager regionManager,
            IUnityContainer unityContainer,
            IDialogService dialogService) : base(regionManager, unityContainer, dialogService)
        {
            _achievementService = achievementService;
            _itemListService = itemListService;
            _tempServ = tempServ;
            InitExportTemplateTypes();
            InitViewGroupMode();
            LoadPropertyInfos();
        }

        public ObservableCollection<ComboBoxItemModel<Report>> TemplateComboxList
        {
            get { return _templateList; }
            set { SetProperty(ref _templateList, value); }
        }

        public ComboBoxItemModel<Report> SelectedTemplateModel
        {
            get { return _templateSelectObj; }
            set { SetProperty(ref _templateSelectObj, value); }
        }

        public GroupMode SelectedModel
        {
            get { return _groupMode; }
            set { SetProperty(ref _groupMode, value); }
        }

        public List<ComboBoxItemModel<GroupMode>> GroupModelList { get; set; } = new List<ComboBoxItemModel<GroupMode>>();


        public ICommand ModelSelectChangedCommand
        {
            get
            {
                if (_modelSelectChangedCommand != null) return _modelSelectChangedCommand;
                _modelSelectChangedCommand = new DelegateCommand<object>(onModelSelectChangedCommand);
                return _modelSelectChangedCommand;
            }
        }

        public ICommand AddItemCommand
        {
            get
            {
                if (_addItemCommand != null) return _addItemCommand;
                _addItemCommand = new DelegateCommand<object>(onAddItemCommand);
                return _addItemCommand;
            }
        }

        public ICommand ExportFileCommand
        {
            get
            {
                if (_exportFileCommand != null) return _exportFileCommand;
                _exportFileCommand = new DelegateCommand<object>(onExportFileCommand);
                return _exportFileCommand;
            }
        }

        protected override async void OnInitPage(object obj)
        {
            var itemLists = await _itemListService.GetItemListBomAsync(GlobalObject.CurrentProject.ProjId.ToString(), GroupMode.mode2);
            DataList.Clear();
            DataList.AddRange(itemLists);
        }

        private void InitViewGroupMode()
        {
            GroupModelList.Add(new ComboBoxItemModel<GroupMode>
            {
                Description = "默认视图模式",
                Name = "默认视图模式",
                SelectedModel = GroupMode.mode0,
            });
            GroupModelList.Add(new ComboBoxItemModel<GroupMode>
            {
                Description = "分组视图模式1",
                Name = "分组视图模式1",
                SelectedModel = GroupMode.mode1,
            });
            GroupModelList.Add(new ComboBoxItemModel<GroupMode>
            {
                Description = "分组视图模式2",
                Name = "分组视图模式2",
                SelectedModel = GroupMode.mode2,
            });
        }

        private async void InitExportTemplateTypes()
        {
            _templateList = new ObservableCollection<ComboBoxItemModel<Report>>();
            var list = await _tempServ.GetTemplateLisAsync(GlobalObject.CurrentProject.ProjId.ToString());
            list = list.Where(x => x.Type == (TemplateType)templateType).ToList();
            TemplateComboxList.Clear();
            TemplateComboxList.Add(new ComboBoxItemModel<Report>
            {
                Name = "未选择模板",
                Description = "未选择模板",
                IsEnable = true,
                SelectedModel = new Report { Name = "" }
            });
            foreach (var item in list)
            {
                TemplateComboxList.Add(new ComboBoxItemModel<Report>
                {
                    Description = item.Description,
                    IsEnable = true,
                    Name = item.Name,
                    SelectedModel = item
                });
            }
        }



        protected override async void LoadPropertyInfos()
        {
            if (_itemListService == null) return;
            var columns = await _itemListService.InitPropertyInfosAsync(GlobalObject.CurrentProject.ProjId.ToString(), _groupMode);

            _dynamicPropertyInfos.Clear();
            _dynamicPropertyInfos.AddRange(columns);
        }

        private void onModelSelectChangedCommand(object obj)
        {
            var eventArgs = obj as SelectionChangedEventArgs;
            if (eventArgs == null)
                return;
            if (eventArgs.AddedItems.Count < 1)
                return;

            var selectObj = eventArgs.AddedItems[0] as ComboBoxItemModel<GroupMode>;

            if (selectObj.SelectedModel == SelectedModel)
                return;
            this.SelectedModel = selectObj.SelectedModel;

            LoadPropertyInfos();

            Columns = GetGridColumns(_dynamicPropertyInfos);
            GroupDescriptors = GetGroupDescriptors(_dynamicPropertyInfos);

            OnInitPage(null);
        }

        private async void onExportFileCommand(object obj)
        {
            var saveFileDialog = new SaveFileDialog
            {
                Filter = "Excel文件 *.xlsx|*.xlsx"
            };
            var templateType = SelectedTemplateModel;
            var groupMode = SelectedModel;

            if (templateType == null)
            {
                Dialog.ShowAltert("导出失败：未选择任何导出模板！！！");
                return;
            }

            if (templateType.SelectedModel.Name.IsNullOrEmpty())
            {
                Dialog.ShowAltert("导出失败：未选择任何导出模板！！！");
                return;
            }

            var result = saveFileDialog.ShowDialog();
            if (result != System.Windows.Forms.DialogResult.OK) return;

            try
            {
                var rr = await _achievementService.ExportItemListBomAsync(GlobalObject.CurrentProject.ProjId.ToString(), groupMode, templateType.SelectedModel);
                if (!rr.succeeded)
                {
                    LoggerHelper.Current.Error(rr.errors.ToString());
                    Dialog.ShowAltert(rr.errors.ToString());
                    return;
                }
                using var stream = rr.data;
                await FileHelper.WriteFileStreamAsync(stream, saveFileDialog.FileName);
            }
            catch (Exception x)
            {
                var msg = $"导出失败：{x.Message}";
                Dialog.ShowAltert(msg);
            }
        }

        private void onAddItemCommand(object obj)
        {

        }
    }
}
